package cn.nubia.admin.sysconfig.service;

import cn.nubia.admin.common.mybatis.bean.Query;
import cn.nubia.admin.common.mybatis.service.BaseServiceImpl;
import cn.nubia.admin.sysconfig.bean.SystemLog;
import cn.nubia.admin.sysconfig.bean.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2015/7/15.
 */
@Service
public class UserResourceService extends BaseServiceImpl<UserResource> {

    @Autowired
    SystemLogService systemLogService;

    /**
     * 保存用户权限.
     *
     * @param userResource 保存用户权限.
     */
    public void save(UserResource userResource) {
        if (null == userResource.getId()) {
            insert(userResource);
            systemLogService.log(SystemLog.ModuleTypeEnum.USERRESOURCELIST, SystemLog.OperateTypeEnum.ADD, userResource.getId());

        } else {
            update(userResource);
            systemLogService.log(SystemLog.ModuleTypeEnum.USERRESOURCELIST, SystemLog.OperateTypeEnum.EDIT, userResource.getId());

        }
    }

    /**
     * 通过用户id获取用户权限
     *
     * @param userId 用户id
     * @return 用户权限属性
     */
    public UserResource get(Integer userId) {
        if (null == userId) {
            return null;
        }

        Query<UserResource> query = Query.build(UserResource.class);
        query.addEq("userId", userId);
        return get(query);
    }


    public void saveUserResource(UserResource userResource) {
        //取得存在的资源.
        UserResource resource = get(userResource.getUserId());

        if (null == resource) {
            insert(userResource);
            systemLogService.log(SystemLog.ModuleTypeEnum.USERRESOURCELIST, SystemLog.OperateTypeEnum.ADD, userResource.getId());
        } else {
            String resourceIds = resource.getResourceIds();
            if (resourceIds == null) {
                resourceIds = userResource.getResourceIds();
            } else {
                resourceIds = resourceIds + "," + userResource.getResourceIds();
            }
            resource.setResourceIds(resourceIds);
            update(resource);
            systemLogService.log(SystemLog.ModuleTypeEnum.USERRESOURCELIST, SystemLog.OperateTypeEnum.EDIT, userResource.getId());

        }

    }

    public void deleteUserResource(UserResource userResource) {
        //取得存在的资源.
        UserResource resource = get(userResource.getUserId());

        if (null != resource) {
            String resourceIds = resource.getResourceIds();
            resourceIds = resourceIds.replaceAll(userResource.getResourceIds(), "");
            resourceIds = resourceIds.replaceAll(",,", ",");
            resource.setResourceIds(resourceIds);
            update(resource);
            systemLogService.log(SystemLog.ModuleTypeEnum.USERRESOURCELIST, SystemLog.OperateTypeEnum.DEL, userResource.getId());

        }
    }
}
